<?php
/**附件控制器
 * @Author: 976123967@qq.com
 * @Date:   2015-07-16 15:30:10
 * @Last Modified by:   cl
 * @Last Modified time: 2015-10-11 20:55:11
 */

namespace Admin\Controller;

use Think\Upload;
use OSS\Client;

class UploadController extends PublicController
{
    /**
     * [do_upload 执行上传]
     * @return [type] [description]
     */
    public function do_upload()
    {
           header("content:application/json;chartset=uft-8");
     // 上传格式
     $ext = I('post.ext');
     // 要求上传的是不是图片
     $isPic = I('post.is_pic');
     //上传文件
     $upload = new Upload();             // 实例化上传类
     $upload->maxSize  = 314572800 ;     // 设置附件上传大小
     $upload->exts  = explode('|', $ext);// 设置附件上传类型
     $upload->autoSub =false;            //不要自动创建子目录
     $upload->rootPath = './Data/Uploads/'; //设置上传根路径 这个系统不会自动创建
     if($isPic)
      $upload->savePath = 'image/'.date('Y').'/'.date('m').'/'.date('d').'/';
     else
      $upload->savePath = 'file/'.date('Y').'/'.date('m').'/'.date('d').'/';
     $result = ["code"=>0,"message"=>"success","data"=>[]];
     if($info=$upload->uploadOne($_FILES['file']))
        {
         // 上传成功服务器地址
          $pic = $upload->rootPath.$info['savepath'].$info['savename'];
          $file = pathinfo($pic);

          // 文件原名称
          $name = $_FILES['file']['name'];
          $data = array(
           'remark'=>$name,
           'name'=>$file['basename'],
           'ext'=>$file['extension'],
           'path'=>$file['dirname'],
           'addtime'=>time(),
           'user_uid'=>session('user_id'),
           'size'=>filesize($pic)
          );
          $id = $this->model->add($data);
           $result["data"]["id"] = $id;
           $result["data"]["src"] = $pic;

        }
        else
           {
               $result["code"] = -1;
               $result["message"] = $upload->getError();
           }

           echo json_encode($result);
        die;
    }

    public function uploadFile()
    {
        /*header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");*/
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if (!empty($_POST['debug'])) {
            $random = rand(0, intval($_POST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

        @set_time_limit(0);

        $targetDir = 'Data/Uploads/file_tmp/' . date('Y') . '/' . date('m') . "/" . date('d');
        $uploadDir = 'Data/Uploads/file/' . date('Y') . '/' . date('m') . "/" . date('d');

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge       = 5 * 3600; // Temp file age in seconds
        $mode             = 0777; // 0777 权限

        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir, $mode, true);
            @chmod($targetDir, $mode);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir, $mode, true);
            @chmod($uploadDir, $mode);
        }
        // Get a file name
        if (isset($_POST["name"])) {
            $fileName = $_POST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $pathInfo = pathinfo($fileName);
        if (!in_array($pathInfo["extension"], ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'rar', 'zip', '7z'])) {
            echo json_encode(['status' => 403, 'result' => ['message' => '格式不对']]);
            return;
        }
        $oldName  = $fileName;
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
        // Chunking might be enabled
        $chunk  = isset($_POST["chunk"]) ? intval($_POST["chunk"]) : 0;
        $chunks = isset($_POST["chunks"]) ? intval($_POST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                echo json_encode(['status' => 100, 'result' => ["message" => 'Failed to open temp directory.']]);
                return;
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            echo json_encode(['status' => 102, 'result' => ["message" => 'Failed to open output stream.']]);
            return;
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                echo json_encode(['status' => 103, 'result' => ["message" => 'Failed to move uploaded file.']]);
                return;
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                echo json_encode(['status' => 101, 'result' => ["message" => 'Failed to open input stream.']]);
                return;
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                echo json_encode(['status' => 101, 'result' => ["message" => 'Failed to open input stream.']]);
                return;
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done  = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }

        if ($done) {
            $pathInfo   = pathinfo($fileName);
            $hashStr    = substr(md5($pathInfo['basename']), 8, 16);
            $hashName   = time() . $hashStr . '.' . $pathInfo['extension'];
            $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $hashName;

            if (!$out = @fopen($uploadPath, "wb")) {
                echo json_encode(['status' => 102, 'result' => ["message" => 'Failed to open output stream.']]);
                return;
            }
            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            @fclose($out);
            $response = [
                'success'      => true,
                'oldName'      => $oldName,
                'filePath'     => './' . $uploadPath,
                'fileSuffixes' => $pathInfo['extension'],
                'hashName'     => $hashName
            ];


            $data = array(
                'remark'   => $oldName,              // 文件原名称
                'name'     => basename($uploadPath), // 服务器名称
                'ext'      => $pathInfo['extension'],
                'path'     => './' .dirname($uploadPath),
                'addtime'  => time(),
                'user_uid' => session('user_id'),
                'size'     => filesize($uploadPath)
            );
            $this->model->add($data);

            // 当status返回1时，为上传成功，其他则失败
            echo json_encode(['status' => 1, 'result' => ['message' => '上传成功', 'info' => $response]]);
            return;

        }
        echo json_encode(['status' => 200, 'result' => ['message' => '上传成功中']]);
    }


    /**
     * [_search 设置查询条件]
     * @return [type] [description]
     */
    public function _search()
    {

        $fields = $this->model->getDbFields();
        if ($fields) {
            foreach ($fields as $v) {
                if (I('get.' . $v))
                    $map[$v] = I('get.' . $v);
            }
        }

        $keyword = I('get.keyword');

        if ($keyword) {
            $map['remark'] = array('like', '%' . $keyword . '%');
        }

        $status = I('get.status');
        switch ($status) {

            case 2:
                $map['relation'] = '';
                break;
            case 1:
                $map['relation'] = array('neq', '');

                break;

        }


        $startTime      = I('get.start_time');
        $controllerName = strtolower(CONTROLLER_NAME);
        if ($startTime)
            $map[] = $controllerName . '.addtime >= ' . strtotime($startTime);
        $endTime = I('get.end_time');
        if ($endTime)
            $map[] = $controllerName . '.addtime <= ' . (strtotime($endTime) + 3600 * 24);
        $endTime = I('get.end_time');

        $ext = I('get.ext');
        if ($ext)
            $map['ext'] = $ext;
        return $map;

    }

    /**
     * [_list 列表]
     * @return [type] [description]
     */
    public function _list()
    {

        // 排序字段 默认为表的主键
        $order = I('post._order', $this->model->getPk());


        // 排序方式 默认为降序排列
        $sort = I('post._sort', 'desc');
        // 统计
        $controllerName = strtolower(CONTROLLER_NAME);
        $dbLogic        = D(CONTROLLER_NAME . 'View', 'Logic');
        $count          = $dbLogic->where($this->map)->count();
        if ($count > 0) {
            import('ORG.Util.Page');
            // 每页显示记录数
            $listRows = I('post.numPerPage', C('PAGE_LISTROWS'));
            // 实例化分页类 传入总记录数和每页显示的记录数
            $page = new \Think\Page($count, $listRows);
            // 当前页数
            $currentPage = I(C('VAR_PAGE'), 1);
            // 进行分页数据查询
            $worder[$order] = $sort;


            $data = $dbLogic->where($this->map)->order($worder)->page($currentPage . ',' . $listRows)->select();
            foreach ($data as $k => $v) {
                $ext = explode('|', C('cfg_image'));
                if (in_array($v['ext'], $ext)) {

                    $data[$k]['is_jpg']  = 1;
                    $data[$k]['preview'] = '<img src="' . __ROOT__ . '/Data/Public/admin/images/ext/jpg.gif" />';
                } else {
                    $data[$k]['is_jpg']  = 0;
                    $data[$k]['preview'] = '<img src="' . __ROOT__ . '/Data/Public/admin/images/ext/' . $v['ext'] . '.gif"  />';
                }
            }
            // 分页显示输出
            $show = $page->show();

            //列表排序显示
            //排序图标
            $sortImg = $sort;
            //排序提示
            $sortAlt = $sort == 'desc' ? '降序排列' : '升序排列';
            //排序方式
            $sort = $sort == 'desc' ? 1 : 0;

            //模板赋值
            $this->assign('data', $data);
            $this->assign('sort', $sort);
            $this->assign('order', $order);
            $this->assign('sortImg', $sortImg);
            $this->assign('sortType', $sortAlt);
            $this->assign('page', $show);
            $this->assign('totalCount', $count);
            $this->assign('numPerPage', $listRows);
            $this->assign('currentPage', $currentPage);
        }
    }

    /**
     * [bathdelete 批量删除]
     * @return [type] [description]
     */
    public function bathdelete()
    {
        $id = I('post.id');

        $id = implode(',', $id);

        $this->model->del($id);
        $this->success('删除成功', U('index'));
    }


}